import React, { useEffect } from 'react'
import styles from './index.module.scss'
import { createRoot } from 'react-dom/client'
import message from '@c/message'
import cm from 'classnames'
import { useState } from 'react'
import { dianboGetSource } from '@/api/vod'

const cacheArr = []
const Index = props => {
  const { type = '', content = '', cid, vEid, onClose, ep, delay = 5000 } = props
  const [closed, setClosed] = useState(false)
  const messageClass = cm(styles.message, { [styles.closed]: closed })
  const close = () => {
    setClosed(true)
    setTimeout(() => {
      cacheArr.splice(0, 1)
      onClose()
    }, 300)
  }
  // 求片
  const getUrl = async () => {
    close()
    const currMovie = vEid
    const res = await dianboGetSource({
      cid: parseInt(cid),
      eid: currMovie.eid,
      eporder: ep
    })
    if (res.code === 0) {
      message({ content: '已收到您的催促，加急处理中~' })
    }
  }

  useEffect(() => {
    const t = setTimeout(close, delay)
    return () => {
      t && clearTimeout(t)
    }
  }, [])

  return (
    <div className={messageClass}>
      {['not-vip', 'vip', 'kadun', 'switch'].includes(type) && (
        <div className={styles.playToast}>
          <img src="/images/warn.webp" alt="" />
          <span>{content}</span>
        </div>
      )}
      {type === 'normal' && (
        <div className={styles.playToast}>
          <img src="/images/warn.webp" alt="" />
          <span>视频为三方资源，请勿相信视频中的任何广告</span>
        </div>
      )}
      {type === 'onlyNormal' && (
        <div className={styles.playToast}>
          <img src="/images/warn.webp" alt="" />
          <span>最优线路正在入库，已为您起播普通线路</span>
          <span className={styles.playOrder} onClick={getUrl}>
            催一下
          </span>
        </div>
      )}
    </div>
  )
}

const getContainer = () => {
  const root = document.querySelector('#play-toast')
  return root
}

const _message = props => {
  // 已存在的不进入
  if (cacheArr.find(item => item === props.type)) {
    return
  }

  // 播放卡顿处理，只有当cacheArr里面没有内容的时候才展示
  if ('kadun' === props.type && cacheArr.length) {
    return
  }
  cacheArr.push(props.type)
  const messageRoot = getContainer()
  const _dom = document.createElement('div')
  messageRoot.insertBefore(_dom, messageRoot.firstChild)

  const handleClose = () => {
    root.unmount()
    _dom.remove()
  }
  const root = createRoot(_dom)
  root.render(<Index {...props} onClose={handleClose} />)
}

export default _message
